<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>产品库存 - 智慧农业信息管理系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f8f9fa;
        }
        
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .navbar-brand, .navbar-nav .nav-link {
            color: white !important;
        }
        
        .sidebar {
            position: fixed;
            top: 56px;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 20px 0;
            background: white;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            overflow-y: auto;
        }
        
        .sidebar .nav-link {
            color: #333;
            padding: 12px 20px;
            border-left: 3px solid transparent;
            transition: all 0.3s;
        }
        
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: #667eea;
            background-color: #f8f9fa;
            border-left-color: #667eea;
        }
        
        .sidebar .nav-link i {
            width: 20px;
            margin-right: 10px;
        }
        
        main {
            margin-top: 56px;
            padding-top: 20px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
        }
        
        .btn-primary:hover {
            opacity: 0.9;
        }
        
        .product-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 20px;
        }
        
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .product-image-placeholder {
            width: 100%;
            height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-size: 3rem;
        }
        
        .product-body {
            padding: 20px;
        }
        
        .product-name {
            font-size: 1.2rem;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }
        
        .product-info {
            color: #666;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }
        
        .product-badge {
            display: inline-block;
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 0.85rem;
            font-weight: bold;
        }
        
        .badge-grade-A {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }
        
        .badge-grade-B {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }
        
        .badge-grade-C {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
            color: white;
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .image-preview {
            max-width: 100%;
            max-height: 300px;
            margin-top: 10px;
            border-radius: 8px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="/index">
                <i class="fas fa-leaf"></i> 智慧农业信息管理系统
            </a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text text-white me-3">
                    <i class="fas fa-user-circle"></i>
                    欢迎，<span th:text="${session.currentUser.realName}">用户</span>
                </span>
                <a class="nav-link text-white" href="/logout">
                    <i class="fas fa-sign-out-alt"></i> 退出
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-md-block sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/index">
                                <i class="fas fa-home"></i> 首页
                            </a>
                        </li>
                        
                        <!-- 管理员菜单 -->
                        <div th:if="${session.currentUser.role == 'admin'}">
                            <li class="nav-item">
                                <a class="nav-link" href="/user/list">
                                    <i class="fas fa-users"></i> 用户管理
                                </a>
                            </li>
                        </div>
                        
                        <!-- 农场主和管理员菜单 -->
                        <div th:if="${session.currentUser.role == 'admin' || session.currentUser.role == 'manager'}">
                            <li class="nav-item">
                                <a class="nav-link" href="/field/list">
                                    <i class="fas fa-map"></i> 地块管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/crop/list">
                                    <i class="fas fa-seedling"></i> 作物管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/material/list">
                                    <i class="fas fa-boxes"></i> 农资管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/plan/list">
                                    <i class="fas fa-calendar-alt"></i> 种植计划
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/farming/list">
                                    <i class="fas fa-tractor"></i> 农事记录
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/monitor/list">
                                    <i class="fas fa-chart-line"></i> 生长监测
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/product/list">
                                    <i class="fas fa-box"></i> 产品管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/sales/list">
                                    <i class="fas fa-shopping-cart"></i> 销售记录
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/statistics/dashboard">
                                    <i class="fas fa-chart-bar"></i> 数据统计
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/news/list">
                                    <i class="fas fa-bullhorn"></i> 新闻公告
                                </a>
                            </li>
                        </div>
                        
                        <!-- 所有用户可见 -->
                        <li class="nav-item">
                            <a class="nav-link" href="/farm/display">
                                <i class="fas fa-store"></i> 农场展示
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-10 ms-sm-auto px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3">
                    <h1 class="h2"><i class="fas fa-box"></i> 产品库存管理</h1>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#productModal" onclick="resetForm()">
                        <i class="fas fa-plus"></i> 新增产品
                    </button>
                </div>

                <!-- 产品卡片展示 -->
                <div class="row">
                    <div th:if="${products != null and !products.isEmpty()}">
                        <div class="col-md-4" th:each="product : ${products}">
                            <div class="product-card">
                                <div th:if="${product.image != null and product.image != ''}">
                                    <img th:src="${product.image}" class="product-image" alt="产品图片">
                                </div>
                                <div th:if="${product.image == null or product.image == ''}" class="product-image-placeholder">
                                    <i class="fas fa-box-open"></i>
                                </div>
                                <div class="product-body">
                                    <div class="product-name" th:text="${product.productName}">产品名称</div>
                                    <div class="product-info">
                                        <i class="fas fa-barcode"></i> 编号: <span th:text="${product.productCode}">编号</span>
                                    </div>
                                    <div class="product-info">
                                        <span class="product-badge" 
                                              th:classappend="${product.grade == 'A' ? 'badge-grade-A' : (product.grade == 'B' ? 'badge-grade-B' : 'badge-grade-C')}"
                                              th:text="${product.grade + '级'}">等级</span>
                                        <span class="ms-2">
                                            <i class="fas fa-warehouse"></i> 库存: 
                                            <strong th:text="${product.quantity}">0</strong>
                                            <span th:text="${product.unit}">单位</span>
                                        </span>
                                    </div>
                                    <div class="product-info">
                                        <i class="fas fa-map-marker-alt"></i> 产地: <span th:text="${product.origin}">产地</span>
                                    </div>
                                    <div class="product-info">
                                        <i class="fas fa-calendar"></i> 收获: 
                                        <span th:text="${#temporals.format(product.harvestDate, 'yyyy-MM-dd')}">日期</span>
                                    </div>
                                    <div class="product-info">
                                        <i class="fas fa-tags"></i> 
                                        成本: <strong class="text-danger">¥<span th:text="${product.costPrice}">0</span></strong> / 
                                        售价: <strong class="text-success">¥<span th:text="${product.suggestedPrice}">0</span></strong>
                                    </div>
                                    <div class="mt-3 d-flex justify-content-between">
                                        <button class="btn btn-sm btn-outline-primary" 
                                                th:onclick="'editProduct(' + ${product.id} + ')'">
                                            <i class="fas fa-edit"></i> 编辑
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" 
                                                th:onclick="'deleteProduct(' + ${product.id} + ')'">
                                            <i class="fas fa-trash"></i> 删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div th:if="${products == null or products.isEmpty()}" class="col-12">
                        <div class="alert alert-info text-center">
                            <i class="fas fa-info-circle fa-2x mb-2"></i>
                            <p>暂无产品信息，请点击"新增产品"按钮添加</p>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 产品编辑模态框 -->
    <div class="modal fade" id="productModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-box"></i> 产品信息
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="productForm">
                        <input type="hidden" id="productId" name="id">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">产品名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="productName" name="productName" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">产品编号 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="productCode" name="productCode" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">等级 <span class="text-danger">*</span></label>
                                <select class="form-select" id="grade" name="grade" required>
                                    <option value="A">A级 - 特级</option>
                                    <option value="B">B级 - 一级</option>
                                    <option value="C">C级 - 二级</option>
                                    <option value="D">D级 - 三级</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">单位 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="unit" name="unit" placeholder="如：kg, 斤, 箱" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">库存数量 <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="quantity" name="quantity" step="0.01" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">产地</label>
                                <input type="text" class="form-control" id="origin" name="origin">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">收获日期</label>
                                <input type="date" class="form-control" id="harvestDate" name="harvestDate">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">保质期（天）</label>
                                <input type="number" class="form-control" id="shelfLife" name="shelfLife">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">成本价</label>
                                <input type="number" class="form-control" id="costPrice" name="costPrice" step="0.01">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">建议售价</label>
                                <input type="number" class="form-control" id="suggestedPrice" name="suggestedPrice" step="0.01">
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">产品图片</label>
                                <input type="file" class="form-control" id="imageFile" accept="image/*" onchange="previewImage(this)">
                                <input type="hidden" id="image" name="image">
                                <img id="imagePreview" class="image-preview" style="display: none;">
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">产品描述</label>
                                <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveProduct()">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        function resetForm() {
            $('#productForm')[0].reset();
            $('#productId').val('');
            $('#imagePreview').hide().attr('src', '');
            $('#image').val('');
        }

        function previewImage(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                const formData = new FormData();
                formData.append('file', file);

                // 上传图片
                $.ajax({
                    url: '/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.code === 200) {
                            $('#image').val(res.data);
                            $('#imagePreview').attr('src', res.data).show();
                        } else {
                            alert('图片上传失败: ' + res.message);
                        }
                    },
                    error: function() {
                        alert('图片上传失败，请重试');
                    }
                });
            }
        }

        function saveProduct() {
            const formData = {
                id: $('#productId').val() || null,
                productName: $('#productName').val(),
                productCode: $('#productCode').val(),
                grade: $('#grade').val(),
                unit: $('#unit').val(),
                quantity: parseFloat($('#quantity').val()),
                origin: $('#origin').val(),
                harvestDate: $('#harvestDate').val(),
                shelfLife: $('#shelfLife').val() ? parseInt($('#shelfLife').val()) : null,
                costPrice: $('#costPrice').val() ? parseFloat($('#costPrice').val()) : null,
                suggestedPrice: $('#suggestedPrice').val() ? parseFloat($('#suggestedPrice').val()) : null,
                image: $('#image').val(),
                description: $('#description').val()
            };

            $.ajax({
                url: '/product/save',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    if (res.code === 200) {
                        alert('保存成功！');
                        location.reload();
                    } else {
                        alert('保存失败: ' + res.message);
                    }
                },
                error: function() {
                    alert('保存失败，请重试');
                }
            });
        }

        function editProduct(id) {
            $.get('/product/detail/' + id, function(res) {
                if (res.code === 200) {
                    const p = res.data;
                    $('#productId').val(p.id);
                    $('#productName').val(p.productName);
                    $('#productCode').val(p.productCode);
                    $('#grade').val(p.grade);
                    $('#unit').val(p.unit);
                    $('#quantity').val(p.quantity);
                    $('#origin').val(p.origin);
                    $('#harvestDate').val(p.harvestDate);
                    $('#shelfLife').val(p.shelfLife);
                    $('#costPrice').val(p.costPrice);
                    $('#suggestedPrice').val(p.suggestedPrice);
                    $('#image').val(p.image);
                    $('#description').val(p.description);
                    if (p.image) {
                        $('#imagePreview').attr('src', p.image).show();
                    }
                    $('#productModal').modal('show');
                } else {
                    alert('获取产品信息失败');
                }
            });
        }

        function deleteProduct(id) {
            if (confirm('确定要删除这个产品吗？')) {
                $.ajax({
                    url: '/product/delete/' + id,
                    type: 'POST',
                    success: function(res) {
                        if (res.code === 200) {
                            alert('删除成功！');
                            location.reload();
                        } else {
                            alert('删除失败: ' + res.message);
                        }
                    },
                    error: function() {
                        alert('删除失败，请重试');
                    }
                });
            }
        }
    </script>
</body>
</html>
